package okl.tdf.app.services
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.events.PropertyChangeEvent;
	import mx.messaging.Consumer;
	import mx.messaging.events.ChannelEvent;
	import mx.messaging.events.MessageEvent;
	import mx.messaging.events.MessageFaultEvent;
	
	import okl.tdf.app.controller.messages.FeedResultMessage;
	import okl.tdf.app.model.vo.SampleRequest;

	/**
	 *	@author "oleksandr.kulinchenko@gmail.com"
	 */
	//[ManagedEvents("contactSaved,contactDeleted")]
	public class TdfFeedServiceImpl extends EventDispatcher implements ITdfFeedService
	{
		public function TdfFeedServiceImpl()
		{
		}
		
		[Inject(id="tdfConsumer")]
		public var service:Consumer;

		[Init]public function init():void{
			service.addEventListener(MessageEvent.MESSAGE, messageHandler);
			service.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onServicePropertyChange);
			service.addEventListener(MessageFaultEvent.FAULT, onMessageFault);
		}
		
		//{region MESSAGE_DISPATCHERS
		[MessageDispatcher]public var sendMessage:Function;
		
		protected function onServicePropertyChange(event:PropertyChangeEvent):void{
			if(event.property=="subscribed" && event.newValue==false){
				var msg:FeedResultMessage = new FeedResultMessage();
				msg.subscribed=false;
				sendMessage(msg);
			}
		}
		
		protected function messageHandler(event:MessageEvent):void  
		{  
			var feedItem:SampleRequest = event.message.body as SampleRequest;
			if(!service.subscribed || feedItem==null)return
			var msg:FeedResultMessage = new FeedResultMessage();
			msg.result=feedItem;
			sendMessage(msg);
		}
		
		protected function onMessageFault(event:MessageFaultEvent):void {
			var msg:FeedResultMessage = new FeedResultMessage();
			msg.error=event;
			sendMessage(msg);			
		}
		//}endregion
		
		//{region CLASS_INTERFACE
		public function startViewsFeed():void{
			trace("================start==================");
			service.subscribe();		
		}
		
		public function stopViewsFeed():void{
			trace("================stop==================");
			if(service.subscribed)service.unsubscribe();
		}
		//}endregion
	}
}